package com.aWei.springbootinit.job.once;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aWei.springbootinit.esdao.PostEsDao;
import com.aWei.springbootinit.model.entity.Post;
import com.aWei.springbootinit.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

/**
 * @author 小维哥
 * @version 1.2 爬虫单次获取表单post的初始化数据
 */
//@Component            加上次标签自动初始化，开启任务
@Slf4j
public class FetchInitPostList  implements CommandLineRunner {
        @Resource
        private  PostService postService;
        @Resource
        private PostEsDao postEsDao;

        @Override
        public void run(String... args) throws Exception {
                String json = "{\"current\":1,\"pageSize\":40,\"sortField\":\"createTime\",\"sortOrder\":\"descend\",\"reviewStatus\":1,\"category\":\"智能对话\"}";
                String url = "https://api.yucongming.com/api/navItem/list/page/vo";
                String result = HttpRequest
                        .post(url)
                        .body(json)
                        .execute()
                        .body();
                //将JSON转换成对象
                Map<String, Object> map = JSONUtil.toBean(result, Map.class);
                JSONObject data = (JSONObject) map.get("data");
                JSONArray records = (JSONArray) data.get("records");
                List<Post> postLIst = new ArrayList();
                for (Object record : records) {
                        JSONObject temp = (JSONObject) record;
                        Post post = new Post();
                        post.setUserId(1L);
                        post.setTitle(temp.getStr("name"));
                        String description = temp.getStr("description")+"地址"+temp.getStr("url");
                        StringJoiner sj = new StringJoiner("地址：");
                        sj.add(temp.getStr("description")).add(temp.getStr("url"));
                        post.setContent(sj.toString());
                        postLIst.add(post);
                }
                System.out.println(postLIst);
                boolean b = postService.saveBatch(postLIst);
                if(b){
                        log.info("初始化获取帖子的条数为："+postLIst.size());
                }else {
                        log.error("初始化获取帖子失败");
                }

        }
}
